package org.chenwang.projects.ehcacheaws;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jets3t.service.S3ServiceException;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.security.AWSCredentials;

import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;

public class AmazonS3BootstrapCacheLoaderImplRestSimple extends
		AmazonS3BootstrapCacheLoader {

	private static final Log log = LogFactory.getLog(AmazonS3BootstrapCacheLoaderImplRestSimple.class);
	
	protected RestS3Service service;
	
	public AmazonS3BootstrapCacheLoaderImplRestSimple(String bucketName,
			String pathName, String pathSeparator, AWSCredentials credentials,
			boolean asynchronous) {
		super(bucketName, pathName, pathSeparator, credentials, asynchronous);
		this.initService();
	}
	
	protected void initService() {
		try {
			this.service = new RestS3Service(this.credentials);
			log.debug("initialised underlying storage service");
		}
		catch (S3ServiceException s3se) {
			log.fatal("error happened when initialising underlying storage access!", s3se);
			this.service = null;
		}
	}

	@Override
	protected Object doClone() throws CloneNotSupportedException {
		return new AmazonS3BootstrapCacheLoaderImplRestSimple(this.bucketName, this.pathName, this.pathSeparator, this.credentials, this.asynchronous);
	}

	@Override
	protected void doLoad(Ehcache cache) throws CacheException {
		if (this.asynchronous) {
			CacheLoaderThread clt = new CacheLoaderThread(cache);
			clt.start();
		}
		else {
			work(cache);
		}
	}
	
	protected void work(Ehcache cache) throws CacheException {
		try {
			S3Object[] objects = this.service.listObjects(new S3Bucket(this.bucketName), this.pathName, this.pathSeparator);
			log.debug("listed all objects from S3");
			
			for (int i = 0; i < objects.length; i ++) {
				S3Object o = objects[i];
				
			}
		}
		catch (S3ServiceException s3se) {
			throw new CacheException("", s3se);
		}
	}
	
	protected final class CacheLoaderThread extends Thread {
		private Ehcache cache;

		public CacheLoaderThread(Ehcache cache) {
			super();
			this.cache = cache;
			this.setDaemon(true);
			this.setName("ehcache-cache-loader-amazon-s3");
			this.setPriority(Thread.NORM_PRIORITY);
		}

		@Override
		public final void run() {
			try {
				work(cache);
			}
			catch (CacheException ce) {
				log.error("error happened when asynchronously loading cache!", ce);
			}
			finally {
				cache = null;
			}
		}
		
	}

}
